package com.example.demo.service.impl;

import com.example.demo.entity.Order;
import com.example.demo.entity.UserService;
import com.example.demo.dto.UserServiceStatusDTO;
import com.example.demo.mapper.UserServiceMapper;
import com.example.demo.service.OrderService;
import com.example.demo.service.UserServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//这是用户购买服务进行实现的服务层
@Service
public class UserServiceServiceImpl implements UserServiceService {
    @Autowired
    private UserServiceMapper userServiceMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private VoicePlanServiceImpl voicePlanServiceImpl;

    public UserService createUserService(String orderNo) {
        UserService userService = new UserService();
        Order order = orderService.getOrder(orderNo);
        userService.setUserId(order.getUserId());
        userService.setStatus(1);
        userService.setExpiryTime(getExpireTime(orderNo,order.getUserId(),order.getServiceId()));
        userServiceMapper.insertUserService(userService);
        return userService;
    }

    // 更新用户服务信息
    public void updateUserService(String orderNo) {
        UserService userService = new UserService();
        Order order = orderService.getOrder(orderNo);
        userService.setUserId(order.getUserId());
        userService.setStatus(1);
        userService.setExpiryTime(getExpireTime(orderNo,order.getUserId(),order.getServiceId()));
        userServiceMapper.updateUserService(userService);
    }
    //检查服务表里面是否有用户
    public boolean existsByUserId(int userId) {
        return userServiceMapper.countByUserId(userId) > 0;
    }
    //获取订单状态
    public int getOrderStatus(String orderNo) {
        return orderService.getOrderStatus(orderNo);
    }

    //获取订单的购买完成时间
    public String getPayTime(String orderNo) {
        int orderStatus = getOrderStatus(orderNo);
        if(orderStatus == 2) {
            //如果订单已支付，那么订单更新时间就是已购买完成时间
            return orderService.getOrderPayTime(orderNo);
        }else
        {
            return null;
        }
    }

    //获取服务时长
    public double getServiceDuration(int id)
    {
        return voicePlanServiceImpl.getDuration(id);
    }

    //计算订单的结束时间，利用完成购买完成时间加上套餐时间
    public String getExpireTime(String orderNo,int userId,int serviceId) {
        // 获取订单支付时间
        String orderPayTimeStr = getPayTime(orderNo);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date orderPayTime = sdf.parse(orderPayTimeStr);

            // 获取服务有效期（以天为单位，可以是double类型）
            double serviceDuration = getServiceDuration(serviceId);

            // 将小时数转换为毫秒
            long durationInMillis = (long) (serviceDuration * 60 * 60 * 1000);

            String expiryTime = userServiceMapper.getExpiryTimeById(userId);
            Date baseTime = orderPayTime;

            if (expiryTime != null && !expiryTime.isEmpty()) {
                Date oldExpireTime = sdf.parse(expiryTime);
                Date now = new Date();
                // 如果原过期时间还未到，则顺延
                if (oldExpireTime.after(now)) {
                    baseTime = oldExpireTime;
                }
            }
            Date newExpireTime = new Date(baseTime.getTime() + durationInMillis);
            return sdf.format(newExpireTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return "时间解析错误";
        }
    }


    //获取购买状态
    public Boolean getIsPurchase(int userId)
    {
        String expiryTime = userServiceMapper.getExpiryTimeById(userId);
        // 处理空值情况
        if (expiryTime == null || expiryTime.isEmpty()) {
            return false; // 如果没有设置过期时间，可以认为服务未购买
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date expiryDate = sdf.parse(expiryTime);
            Date currentDate = new Date();
            return expiryDate.after(currentDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
    private String getExpireTime(int userId)
    {
        return userServiceMapper.getExpiryTimeById(userId);
    }
    //返回购买时间和购买状态
    public UserServiceStatusDTO getIsPurchaseAndExpiryTimeById(int userId) {
        UserServiceStatusDTO userServiceStatusDTO = new UserServiceStatusDTO();
        userServiceStatusDTO.setIsPurchase(getIsPurchase(userId));
        userServiceStatusDTO.setExpiryTime(getExpireTime(userId));
        return userServiceStatusDTO;
    }
}
